package com.jianying.day04;

import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * ClassName: Flink01_Rich_Function
 * Package: com.atguigu.day04
 * Description:
 *
 * @Author: tubage
 * @Create: 2024/4/2 09:09
 * @Version: 1.0
 */
public class Flink01_Rich_Function {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> socketDS = env.socketTextStream("localhost", 8888);
//        env.setParallelism(1);
        env.setParallelism(4);

//        SingleOutputStreamOperator<String> mapDS = socketDS.map(
//                new MapFunction<String, String>() {
//                    @Override
//                    public String map(String s) throws Exception {
//                        return "atguigu:" + s;
//                    }
//                }
//        );

        SingleOutputStreamOperator<String> mapDS = socketDS.map(
                new RichMapFunction<String, String>() {
                    @Override
                    public void open(Configuration parameters) throws Exception {
                        System.out.println("open");
                        RuntimeContext runtimeContext = getRuntimeContext();
                        String name = runtimeContext.getTaskNameWithSubtasks();
                        int index = runtimeContext.getIndexOfThisSubtask();
                        System.out.println("编号：" + index + ",名字：" + name);
                    }

                    @Override
                    public String map(String s) throws Exception {
                        return "atguigu:" + s;
                    }

                    @Override
                    public void close() throws Exception {
                        System.out.println("close");;
                    }
                }
        );

        mapDS.print();

        env.execute();
    }
}
